<template>
  <AppLayout>
    <div :class="styles['user-management']">
      <div :class="styles['page-header']">
        <h1 :class="styles['page-title']">用户管理</h1>
        <button :class="styles['add-user-btn']" @click="showAddUserModal = true">
          <i :class="styles['btn-icon']">➕</i>
          <span>添加用户</span>
        </button>
      </div>

      <div :class="styles['filters']">
        <div :class="styles['search-box']">
          <input v-model="searchQuery" type="text" placeholder="搜索用户..." :class="styles['search-input']">
          <i :class="styles['search-icon']">🔍</i>
        </div>
        <div :class="styles['filter-options']">
          <select v-model="roleFilter" :class="styles['filter-select']">
            <option value="">所有角色</option>
            <option value="admin">管理员</option>
            <option value="teacher">教师</option>
            <option value="student">学生</option>
          </select>
          <select v-model="statusFilter" :class="styles['filter-select']">
            <option value="">所有状态</option>
            <option value="active">活跃</option>
            <option value="inactive">非活跃</option>
          </select>
        </div>
      </div>

      <div :class="styles['users-table']">
        <table>
          <thead>
            <tr>
              <th>用户ID</th>
              <th>用户名</th>
              <th>姓名</th>
              <th>邮箱</th>
              <th>角色</th>
              <th>状态</th>
              <th>创建时间</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="user in filteredUsers" :key="user.id">
              <td>{{ user.id }}</td>
              <td>{{ user.username }}</td>
              <td>{{ user.name }}</td>
              <td>{{ user.email }}</td>
              <td>
                <span :class="[styles['role-badge'], styles[user.role]]">
                  {{ getRoleLabel(user.role) }}
                </span>
              </td>
              <td>
                <span :class="[styles['status-badge'], styles[user.status]]">
                  {{ user.status === 'active' ? '活跃' : '非活跃' }}
                </span>
              </td>
              <td>{{ formatDate(user.createdAt) }}</td>
              <td>
                <div :class="styles['action-buttons']">
                  <button :class="[styles['action-btn'], styles['edit']]" @click="editUser(user)" title="编辑">
                    ✏️
                  </button>
                  <button :class="[styles['action-btn'], styles['delete']]" @click="deleteUser(user.id)" title="删除">
                    🗑️
                  </button>
                  <button :class="[styles['action-btn'], styles['reset']]" @click="resetPassword(user.id)" title="重置密码">
                    🔄
                  </button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <div :class="styles['pagination']">
        <button :class="styles['pagination-btn']" :disabled="currentPage === 1" @click="currentPage--">
          上一页
        </button>
        <span :class="styles['page-info']">第 {{ currentPage }} 页，共 {{ totalPages }} 页</span>
        <button :class="styles['pagination-btn']" :disabled="currentPage === totalPages" @click="currentPage++">
          下一页
        </button>
      </div>
    </div>

    <!-- 用户编辑模态框 -->
    <div v-if="showEditModal" :class="styles['modal-overlay']" @click="showEditModal = false">
      <div :class="styles['modal-content']" @click.stop>
        <div :class="styles['modal-header']">
          <h3>编辑用户</h3>
          <button :class="styles['close-btn']" @click="showEditModal = false">✕</button>
        </div>
        <div :class="styles['modal-body']">
          <form @submit.prevent="saveUser">
            <div :class="styles['form-group']">
              <label>用户名</label>
              <input v-model="editingUser.username" type="text" required>
            </div>
            <div :class="styles['form-group']">
              <label>姓名</label>
              <input v-model="editingUser.name" type="text" required>
            </div>
            <div :class="styles['form-group']">
              <label>邮箱</label>
              <input v-model="editingUser.email" type="email" required>
            </div>
            <div :class="styles['form-group']">
              <label>角色</label>
              <select v-model="editingUser.role" required>
                <option value="admin">管理员</option>
                <option value="teacher">教师</option>
                <option value="student">学生</option>
              </select>
            </div>
            <div :class="styles['form-group']">
              <label>状态</label>
              <select v-model="editingUser.status" required>
                <option value="active">活跃</option>
                <option value="inactive">非活跃</option>
              </select>
            </div>
            <div :class="styles['form-actions']">
              <button type="button" :class="styles['btn-secondary']" @click="showEditModal = false">
                取消
              </button>
              <button type="submit" :class="styles['btn-primary']">
                保存
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </AppLayout>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import AppLayout from '@/components/layout/AppLayout.vue'
import userApi from '@/api/user'
import styles from '@/styles/admin/user-management.module.css'

const users = ref([])
const searchQuery = ref('')
const roleFilter = ref('')
const statusFilter = ref('')
const currentPage = ref(1)
const showEditModal = ref(false)
const editingUser = ref({})

const filteredUsers = computed(() => {
  return users.value.filter(user => {
    const matchesSearch = !searchQuery.value ||
      user.username.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
      user.name.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
      user.email.toLowerCase().includes(searchQuery.value.toLowerCase())

    const matchesRole = !roleFilter.value || user.role === roleFilter.value
    const matchesStatus = !statusFilter.value || user.status === statusFilter.value

    return matchesSearch && matchesRole && matchesStatus
  })
})

const totalPages = computed(() => Math.ceil(filteredUsers.value.length / 10))

const getRoleLabel = (role) => {
  const labels = {
    admin: '管理员',
    teacher: '教师',
    student: '学生'
  }
  return labels[role] || role
}

const formatDate = (date) => {
  return new Date(date).toLocaleDateString('zh-CN')
}

const loadUsers = async () => {
  try {
    const response = await userApi.getUsersByPage({ page: 0, size: 100 })
    users.value = response.data?.content || response.data || []
  } catch (error) {
    console.error('加载用户列表失败:', error)
  }
}

const editUser = (user) => {
  editingUser.value = { ...user }
  showEditModal.value = true
}

const saveUser = async () => {
  try {
    await userApi.updateUser(editingUser.value.id, editingUser.value)
    await loadUsers()
    showEditModal.value = false
  } catch (error) {
    console.error('保存用户失败:', error)
  }
}

const deleteUser = async (userId) => {
  if (confirm('确定要删除这个用户吗？')) {
    try {
      await userApi.deleteUser(userId)
      await loadUsers()
    } catch (error) {
      console.error('删除用户失败:', error)
    }
  }
}

const resetPassword = async (userId) => {
  if (confirm('确定要重置这个用户的密码吗？')) {
    try {
      // 调用重置密码API
      console.log('重置密码:', userId)
    } catch (error) {
      console.error('重置密码失败:', error)
    }
  }
}

onMounted(() => {
  loadUsers()
})
</script>